import axios from "axios";
import * as toast from '@/util/toast/toast'
import User from '../../store/user'
import * as router  from '../router/router'

import { SPApiHttpRequestType } from '../common/spenum'



//请求头类型
const SPApiRequestContentType = {
    JSON : 0,
    FORM_DATA : 1,
    URL_ENCODE : 2,
}

//响应类型
const SPApiResponseType = {
    JSON : 0,
    BLOB : 1,
}

//请求参数
interface requestParam{
    url?:string,
    requestType:number,
    contentType:any,
    responseType:number,
    path:string,
    queryData:any, 
    isShowHUD:boolean,
    isShowSuccessMsg: boolean,
    isShowErrorMsg:boolean
}

//请求参数
interface httpParam{
    url?:string,
    path:string,
    queryData:any, 
    isShowHUD:boolean,
    isShowSuccessMsg: boolean,
    isShowErrorMsg:boolean,
    contentType:any,
}


export default class Api{

    public  baseURL:string;
    public  withCredentials:boolean;
    public  timeout:number;
    public  api:any;
    public  contentType:string = 'json';
    public  responseType:string;

    

    constructor() {
        this.baseURL =  'https://ydpt.wincrosoft.net'
        this.timeout = 10 * 1000
        this.api = null
        this.contentType = 'application/json;charset=UTF-8;';
        this.responseType = "json";
        //跨域请求是否提供凭据信息（cookie、HTTP认证及客户端SSL证明等）,也可以简单理解为跨域类型时是否在请求中携带cookie
        this.withCredentials = false
    }


    //get请求
    get (param: httpParam) {
        return this.request({
            url:param.url,
            requestType:SPApiHttpRequestType.GET,
            path:param.path,
            queryData:param.queryData,
            contentType:param.contentType ? param.contentType : 'FORM_DATA',
            responseType:SPApiResponseType.JSON,
            isShowHUD:param.isShowHUD,
            isShowSuccessMsg:param.isShowSuccessMsg,
            isShowErrorMsg:param.isShowErrorMsg
        }) 
    } 
    //getblob get方式文件流请求
    getBlob (param: httpParam) {
        return this.request({
            url:param.url,
            requestType:SPApiHttpRequestType.GET,
            path:param.path,
            queryData:param.queryData,
            contentType:param.contentType ? param.contentType : 'FORM_DATA',
            responseType:SPApiResponseType.BLOB,
            isShowHUD:param.isShowHUD,
            isShowSuccessMsg:param.isShowSuccessMsg,
            isShowErrorMsg:param.isShowErrorMsg
        })  
    }
    //post请求（请求头为json格式）
    post (param: httpParam) {
        return this.request({
            url:param.url,
            requestType:SPApiHttpRequestType.POST,
            path:param.path,
            queryData:param.queryData,
            contentType:param.contentType ? param.contentType : 'FORM_DATA',
            responseType:SPApiResponseType.JSON,
            isShowHUD:param.isShowHUD,
            isShowSuccessMsg:param.isShowSuccessMsg,
            isShowErrorMsg:param.isShowErrorMsg
        })  
    }
    //postBlob post方式文件流请求
    postBlob (param: httpParam) {
        return this.request({
            url:param.url,
            requestType:SPApiHttpRequestType.POST,
            path:param.path,
            queryData:param.queryData,
            contentType:param.contentType ? param.contentType : 'FORM_DATA',
            responseType:SPApiResponseType.BLOB,
            isShowHUD:param.isShowHUD,
            isShowSuccessMsg:param.isShowSuccessMsg,
            isShowErrorMsg:param.isShowErrorMsg
        })  
    }
    //post请求（请求头为urlEncode格式）
    postUrlEncode(param: httpParam) {
        return this.request({
            url:param.url,
            requestType:SPApiHttpRequestType.POST,
            path:param.path,
            queryData:param.queryData,
            contentType: param.contentType ? param.contentType : 'URL_ENCODE',
            responseType:SPApiResponseType.JSON,
            isShowHUD:param.isShowHUD,
            isShowSuccessMsg:param.isShowSuccessMsg,
            isShowErrorMsg:param.isShowErrorMsg
        })  
    }
    //post请求（请求头为formData格式）
    postFormData(param: httpParam) {
        return this.request({
            url:param.url,
            requestType:SPApiHttpRequestType.POST,
            path:param.path,
            queryData:param.queryData,
            contentType:param.contentType ? param.contentType : 'FORM_DATA',
            responseType:SPApiResponseType.JSON,
            isShowHUD:param.isShowHUD,
            isShowSuccessMsg:param.isShowSuccessMsg,
            isShowErrorMsg:param.isShowErrorMsg
        })  
    }
    //put请求
    put(param: requestParam) {
        return this.request({
            url:param.url,
            requestType:SPApiHttpRequestType.PUT,
            path:param.path,
            queryData:param.queryData,
            contentType:param.contentType ? param.contentType : 'JSON',
            responseType:SPApiResponseType.JSON,
            isShowHUD:param.isShowHUD,
            isShowSuccessMsg:param.isShowSuccessMsg,
            isShowErrorMsg:param.isShowErrorMsg
        }) 
    }
    //delete请求
    delete(param: requestParam) {
        return this.request({
            url:param.url,
            requestType:SPApiHttpRequestType.DELETE,
            path:param.path,
            queryData:param.queryData,
            contentType:param.contentType ? param.contentType : 'JSON',
            responseType:SPApiResponseType.JSON,
            isShowHUD:param.isShowHUD,
            isShowSuccessMsg:param.isShowSuccessMsg,
            isShowErrorMsg:param.isShowErrorMsg
        })  
    }


    //网络请求
    request(param :requestParam ) {
    
        let baseURL =  'https://ydpt.wincrosoft.net'
        let timeout = 10 * 1000
        if(param.url){
            baseURL = param.url
        }
        let url = baseURL.concat(param.path)
    
       
        let contentType = 'JSON' as any
        if(param.contentType === 'FORM_DATA'){
            contentType = SPApiRequestContentType.FORM_DATA
        }else if(param.contentType === 'URL_ENCODE'){
            contentType = SPApiRequestContentType.URL_ENCODE
        }else{
            contentType = 'JSON'
        }

        if(User.getToken().length > 0){
             url = url + '?token=' +User.getToken()

        }
            
        // console.log('路径：'+param.path)
        if(param.queryData && param.path !=='/appapi/User/updatenickname2' && param.path !=='/appapi/User/updaterealname2' && param.path !=='/appapi/Device/add_maintain_record2' && param.path !== '/appapi/Report/report_cumulativedata2'){
            let paramStr = ''
            for(let key in param.queryData){
                paramStr += ('&'+key+'='+param.queryData[key])
            }
            
            if(paramStr !== ''){

                if(User.getToken().length > 0){
                    url += paramStr

                }else{
                    paramStr = paramStr.slice(1,paramStr.length)
                    url += ('?'+paramStr)
                }
               
            }
        }

    
        // console.log('打印出请求地址:' + url)

      

        let headers = {} as any
        headers['token'] = User.getToken()
        headers['Content-Type'] = toRequestContentType(contentType)
        let meth = 'GET'! as any
        switch (param.requestType) {
            case SPApiHttpRequestType.GET:
                meth = 'GET'
                break
            case SPApiHttpRequestType.POST:
                meth = 'POST'
                break
            case SPApiHttpRequestType.PUT:
                meth = 'PUT'
                break
             case SPApiHttpRequestType.DELETE:
                meth = 'DELETE'
                break
            default:
                meth = 'GET'
        }

      

        return new Promise((resolve,reject) => {
            uni.request({
                url: url, //仅为示例，并非真实接口地址。
                data: param.queryData,
                header: headers,
                timeout:timeout,
                method:meth,
                success: (res:any) => {
                    if ( res.data.success || res.data.errcode === 0) {
                        if (param.isShowSuccessMsg) {
                            toast.infoToast(res.data.detail)
                        }
                        resolve(res.data)
                    }else {
                        // console.log(url+'接口200，业务报错：'+JSON.stringify(res.data))

                        let msg =  res.data.detail;
                        if(msg !== null && msg !== undefined && msg !== ''){
                            if (param.isShowErrorMsg) {
                                toast.infoToast(msg)
                            }
                            if(msg.includes('请先登录') || msg.includes('Token不合法')){
                                User.setToken('');
                                router.relaunchHome()
                            }
                        }

                        

                        resolve(res.data);
                    }
                
                },
                fail(result) {
                    let msg = result as any
    
                    // console.log('接口非业务报错：'+JSON.stringify(result))
                    if (param.isShowErrorMsg) {
                        toast.infoToast(msg)
                    }
                    
                    reject(msg);	
                },
            });

        });
        

    }

}




 ///一些转换方法
/**
 * 对象转url query
 * @param paramObj
 */
 function queryString(paramObj:any) {
    if (!paramObj) {
        return ''
      }
      let paramList:any = []
      Object.keys(paramObj) && Object.keys(paramObj).forEach(key => {
        let val = paramObj[key]
        if (val.constructor === Array) {
          val.forEach(_val => {
            paramList.push(key + '=' + _val)
          })
        } else {
          paramList.push(key + '=' + val)
        }
      })
      let str = paramList.join('&')
      return str 
 }
 

 function isNumer (val:any) {
    return typeof val === 'number'
 }

 function isString (val:any) {
    return typeof val === 'string'
 }
 
 function isObject (val:any) {
    return val != null && typeof val === 'object'
 }


//  转换为请求头请求类型
 function toRequestContentType(contentType:number) {
    let contentTypeStr = ''
    switch (contentType) {
        case SPApiRequestContentType.JSON:
            contentTypeStr = 'application/json;charset=UTF-8;';
            break;
        case SPApiRequestContentType.FORM_DATA:
            contentTypeStr = 'multipart/form-data;charset=UTF-8;';
            break;
        case SPApiRequestContentType.URL_ENCODE:
            contentTypeStr = 'application/x-www-form-urlencoded;charset=UTF-8';
            break;
        default:
            contentTypeStr = 'application/json;charset=UTF-8;';
            break;
    }
    return contentTypeStr
 }


//  转换为响应体响应类型
function toResponseType(responseType:number) {
    let responseTypeTypeStr = ''
    switch (responseType) {
        case SPApiResponseType.JSON:
            responseTypeTypeStr = "json";
            break;
        case SPApiResponseType.BLOB:
            responseTypeTypeStr = "blob";
            break;
        default:
            responseTypeTypeStr = "json";
            break;
    }
    return responseTypeTypeStr
 }



 ///把字典拼成参数字符串
 function toUrlEncode (data:any) {
    if (data instanceof Object) {
        let  r = ''
        for (const key in data) {
            r += `${key}=${data[key]}&`
        }
        return r.slice(0,-1)
    } else {
        return data
    }
}